<template>
  <div class="page-header-index-wide">
    <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
      <div class="salesCard">
        <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
          <div class="extra-wrapper" slot="tabBarExtraContent">
            <div class="extra-item">
              <a-select style="width: 140px" v-model="newUser.timeSlot" @change="timeSlotChange">
                <a-select-option value="week">最近七天</a-select-option>
                <a-select-option value="month">最近三十日</a-select-option>
                <a-select-option value="quarter">最近三个月</a-select-option>
                <a-select-option value="custom">自定义</a-select-option>
              </a-select>
            </div>
            <a-range-picker :style="{width: '256px'}"
                            @change="dateChange"
                            v-model="newUser.date"
                            format="YYYY-MM-DD"
                            :disabledDate="disabledDate"
            />
          </div>
          <a-tab-pane :fields="visitFields" loading="true" tab="用户动作" key="1">
            <a-row>
              <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                <bar title="用户动作" :dataSource="barData" yaxisText="动作数"/>
              </a-col>
              <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <rank-list title="动作数排行" :list="rankList"/>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-card>


    <!-- table区域-begin -->
    <div class="margin-tb padding" style="background: #ffffff">
      <h2>每个用户执行的动作次数</h2>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading">

        <span slot="action" slot-scope="text, record">
          <a @click="handleDelete(record.id)">删除</a>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->
  </div>
</template>

<script>
  import ChartCard from '@/components/ChartCard'
  import ACol from 'ant-design-vue/es/grid/Col'
  import ATooltip from 'ant-design-vue/es/tooltip/Tooltip'
  import MiniArea from '@/components/chart/MiniArea'
  import MiniBar from '@/components/chart/MiniBar'
  import MiniProgress from '@/components/chart/MiniProgress'
  import RankList from '@/components/chart/RankList'
  import Bar from '@/components/chart/Bar'
  import LineChartMultid from '@/components/chart/LineChartMultid'
  import HeadInfo from '@/components/tools/HeadInfo.vue'
  import moment from 'moment'

  import Trend from '@/components/Trend'
  import { getLoginfo, getVisitInfo } from '@/api/api'

  let that


  /**数组根据数组对象中的某个属性值进行排序的方法
   * 使用例子：newArray.sort(sortBy('number',false)) //表示根据number属性降序排列;若第二个参数不传递，默认表示升序排序
   * @param attr 排序的属性 如number属性
   * @param rev true表示升序排列，false降序排序
   * */
  function sortBy(attr, rev) {
    //第二个参数没有传递 默认升序排列
    if (rev == undefined) {
      rev = 1
    } else {
      rev = (rev) ? 1 : -1
    }
    return function(a, b) {
      a = a[attr]
      b = b[attr]
      if (a < b) {
        return rev * -1
      }
      if (a > b) {
        return rev * 1
      }
      return 0
    }
  }

  export default {
    name: 'Action',
    components: {
      ATooltip,
      ACol,
      ChartCard,
      MiniArea,
      MiniBar,
      MiniProgress,
      RankList,
      Bar,
      Trend,
      LineChartMultid,
      HeadInfo
    },
    data() {
      return {
        loading: true,
        center: null,
        rankList: [],
        barData: [],
        loginfo: {},
        visitFields: ['ip', 'visit'],
        visitInfo: [],
        newUser: {
          timeSlot: 'week',
          date: []
        },
        dataSource:[],
        // 表头
        columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title: 'ip',
          align:"center",
          dataIndex: 'ip'
        },
        {
          title: '点击了工具试用',
          align:"center",
          dataIndex: '点击了工具试用',
        },
        {
          title: '点击了我要自测',
          align:"center",
          dataIndex: '点击了我要自测',
        },
        {
          title: '点击了免费咨询',
          align:"center",
          dataIndex: '点击了免费咨询',
        },
        {
          title: '点击了解更多',
          align:"center",
          dataIndex: '点击了解更多',
        },
      ],

    }
    },
    created() {
      that = this;
      this.initLogInfo()
      this.initParam()
    },
    methods: {
      initLogInfo() {
        getLoginfo(null).then((res) => {
          if (res.success) {
            Object.keys(res.result).forEach(key => {
              res.result[key] = res.result[key] + ''
            })
            this.loginfo = res.result
          }
        })
        getVisitInfo().then(res => {
          if (res.success) {
            this.visitInfo = res.result
          }
        })
      },

      /**
       * 初始化相关参数
       */
      initParam() {

        //初始化时间设置
        that.setNewUserDate()
      },
      /**
       * 禁止选择的时间段
       */
      disabledDate(current) {
        return current < moment(that.$getDate({ date: new Date(2020, 0, 0) })).endOf('day') || current > moment().endOf('day')
      },
      setNewUserDate(key) {
        let times = 3600 * 24 * 1000 * 7
        switch (key) {
          case 'week':
            times = 3600 * 24 * 1000 * 7
            break
          case 'month':
            times = 3600 * 24 * 1000 * 30
            break
          case 'quarter':
            times = 3600 * 24 * 1000 * 90
            break
          case 'custom':
            return false
            break
          default:
            times = 3600 * 24 * 1000 * 7
            break
        }
        let data = that.$getDate({})
        let data1 = that.$getDate({ date: new Date(new Date().getTime() - times) })
        that.newUser.date = [moment(data1), moment(data)]
        that.getNewUser()
      },

      /**
       * 新增用户数的时间段改变
       */
      timeSlotChange(e) {
        that.setNewUserDate(e)
      },
      dateChange(e) {
        that.newUser.timeSlot = 'custom'
        that.getNewUser()
      },
      getNewUser() {
        that.loading = true;
        let start = moment(that.newUser.date[0]).format('YYYY-MM-DD')
        let end = moment(that.newUser.date[1]).format('YYYY-MM-DD')
        that.getTableData(start,end);
        that.$Request({
          url: '/statistics/actionCount',
          params: {
            start: start,
            end: end
          }
        }).then(res => {
          let rankList = res.result.sort(sortBy('total', false))
          rankList = JSON.parse(JSON.stringify(rankList).replace(/action_name/g, 'name'))
          that.rankList = rankList
          let bar = []
          for (let item of res.result) {
            bar.push({
              x: item.action_name,
              y: item.total
            })
          }
          that.barData = bar
        }).catch(res => {
          if (!res) {
            res = '用户动作数据加载失败'
          }
          that.$message.warning(res)
        }).finally(()=>{
          that.loading = false;
        })
      },
      getTableData(s,e){
        that.loading = true;
        that.$Request({
          url: '/statistics/countAllActionByIp',
          params: {
            start: s,
            end: e
          }
        }).then(res => {
          that.dataSource = res.result;
        }).catch(res => {
          if (!res) {
            res = '用户动作数据加载失败'
          }
          that.$message.warning(res)
        }).finally(()=>{
          that.loading = false;
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .circle-cust {
    position: relative;
    top: 28px;
    left: -100%;
  }

  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

  /* 首页访问量统计 */
  .head-info {
    position: relative;
    text-align: left;
    padding: 0 32px 0 0;
    min-width: 125px;

    &.center {
      text-align: center;
      padding: 0 32px;
    }

    span {
      color: rgba(0, 0, 0, .45);
      display: inline-block;
      font-size: .95rem;
      line-height: 42px;
      margin-bottom: 4px;
    }

    p {
      line-height: 42px;
      margin: 0;

      a {
        font-weight: 600;
        font-size: 1rem;
      }
    }
  }
</style>